const express = require('express');
const router = express.Router();
const pool = require('../models/database.js');


router.post('/createOrder', async (req, res) => {
  try {
    const { orderId, amount, userId } = req.body;
    if (!orderId || !amount || !userId) {
      return res.status(400).json({ code: 400, message: '参数缺失' });
    }

    // 模拟预支付参数生成
    const timeStamp = Math.floor(Date.now() / 1000).toString();
    const nonceStr = Math.random().toString(36).substr(2, 15);
    const packageStr = `prepay_id=mock_prepay_id_${orderId}`;
    const paySign = 'MOCK_PAY_SIGN';

    res.json({
      code: 200,
      data: {
        timeStamp,
        nonceStr,
        package: packageStr,
        signType: 'MD5',
        paySign
      }
    });
  } catch (error) {
    res.status(500).json({ code: 500, message: '服务器错误', error: error.message });
  }
});

router.post('/orderComplete', async (req, res) => {
  try {
    const { orderId, petIds, userId } = req.body;
    if (!orderId || !userId || !Array.isArray(petIds) || petIds.length === 0) {
      return res.status(400).json({ code: 400, message: '参数缺失或格式错误' });
    }

    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 删除流浪动物
      const deleteSql = `DELETE FROM pet_list WHERE id IN (?)`;
      await connection.query(deleteSql, [petIds]);

      // 插入已领养宠物，补充 userId 字段
      const insertSql = `INSERT INTO adopted_pets (pet_id, order_id, user_id, adopted_at) VALUES ?`;
      const now = new Date();
      const values = petIds.map(id => [id, orderId, userId, now]);
      await connection.query(insertSql, [values]);

      await connection.commit();
      connection.release();

      res.json({ code: 200, message: '宠物状态更新成功' });
    } catch (err) {
      await connection.rollback();
      connection.release();
      console.error(err);
      res.status(500).json({ code: 500, message: '数据库操作失败', error: err.message });
    }
  } catch (error) {
    res.status(500).json({ code: 500, message: '服务器错误', error: error.message });
  }
});


module.exports = router;
